package appapi.controller.oider;

import appapi.Request.Basic.DelCompReq;
import appapi.Request.CompPageReq;
import appapi.Global.BusinessException;
import appapi.Request.CompReq;
import appapi.Request.EquipOperPageReq;
import appapi.Request.record.MonthRecPageReq;
import appapi.Vo.AddCompanyVo;
import appapi.Vo.EditCompanyVo;
import appapi.Vo.GetEquipOperPageVo;
import appapi.common.BusinessTypeEnum;
import appapi.common.ResponseBean;
import appapi.config.MyLog;
import appapi.config.CurrentUser;
import appapi.dto.MonthRecModel;
import appapi.entity.Zhongjiao.CompanyDto;
import appapi.entity.Zhongjiao.OrganizationDto;
import appapi.entity.auth.ModulelistEntity;
import appapi.entity.basic.UserInfo;
import appapi.model.ResponseDataModel;
import appapi.model.ResponseModel;
import appapi.service.ICompanyService;
import appapi.service.IOrganization;
import appapi.service.IStaffService;
import appapi.service.RoleService;
import appapi.utils.ExcelUtils;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author djq
 * @date 2023/5/11 14:01
 * @description:
 */
@Api(tags = "基础数据-公司信息")
@RestController
@Validated
@RequestMapping(value = "/api/company")
public class CompanyController {
    @Resource
    private ICompanyService iCompanyService;

    @Autowired
    private IOrganization organization;

    @Resource
    private IStaffService iStaffService;

    /**
     * 新增公司
     *
     * @return
     * @auther djq 2023/5/11
     */
    @ApiOperation(value = "新增公司", notes = "新增公司")
    @PostMapping(value = "/newCompany",produces = "application/json;charset=UTF-8")
    @MyLog(title = "新增公司",businessType = BusinessTypeEnum.insert)
    public ResponseBean insertCompany(@Valid @RequestBody AddCompanyVo companyVo) {
        CompanyDto entity = companyVo.vo2Entity();
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        try {
            int iRet = iCompanyService.InsertCompany(entity);
            if (iRet > 0) {
                //同时增加组织机构
                OrganizationDto dto = new OrganizationDto();
                dto.setOrgaName(entity.getCompName());
                dto.setCreateTime(LocalDateTime.now());
                dto.setUpdateTime(LocalDateTime.now());
                dto.setIsEnable(0);
                dto.setOrgaLevel(1);
                dto.setOrgaPid(1);
                dto.setOrgaNote(entity.getCompNote());
                dto.setOrgaSort(1);
                organization.InsertOrganization(dto);
                //获取组织机构id
                Integer orgaId = Integer.parseInt(dto.getOrgaId().toString());
                entity.setOrgaId(orgaId);
                iCompanyService.UpdateCompany(entity);
                return ResponseBean.success("保存成功！");
            } else {
                return ResponseBean.fail("保存失败！");
            }
        } catch (BusinessException exception) {
            return ResponseBean.fail(exception.getMessage());
        }
    }

    /**
     * 编辑公司
     *
     * @return
     * @auther djq 2023/5/11
     */
    @ApiOperation(value = "编辑公司", notes = "编辑公司")
    @PostMapping(value = "/updateCompany",produces = "application/json;charset=UTF-8")
    @MyLog(title = "编辑公司",businessType = BusinessTypeEnum.update)
    public ResponseBean updateCompany(@Validated @RequestBody EditCompanyVo companyVo) {
        CompanyDto entity = companyVo.vo2Entity();
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        try {
            int iRet = iCompanyService.UpdateCompany(entity);
            if (iRet > 0) {
                //根据ID获取组织机构
                Long orgaId = Long.parseLong(entity.getOrgaId().toString());
                OrganizationDto dto = organization.detail(orgaId);
                //公司ID作为组织机构ID
                if (dto != null) {
                    //同时增加组织机构
                    dto.setOrgaId(orgaId);
                    dto.setOrgaName(entity.getCompName());
                    dto.setUpdateTime(LocalDateTime.now());
                    dto.setOrgaNote(entity.getCompNote());
                    organization.UpdateOrganization(dto);
                } else {
                    //新增组织机构
                    dto = new OrganizationDto();
                    dto.setOrgaName(entity.getCompName());
                    dto.setCreateTime(LocalDateTime.now());
                    dto.setUpdateTime(LocalDateTime.now());
                    dto.setIsEnable(0);
                    dto.setOrgaLevel(1);
                    dto.setOrgaPid(1);
                    dto.setOrgaNote(entity.getCompNote());
                    dto.setOrgaSort(1);
                    organization.InsertOrganization(dto);
                }
                return ResponseBean.success("更新成功！");
            } else {
                return ResponseBean.fail("更新失败！");
            }
        } catch (BusinessException exception) {
            return ResponseBean.fail("更新公司异常！");
        }
    }

    /**
     * 删除公司
     *
     * @return
     * @auther djq 2023/5/11
     */
    @ApiOperation(value = "删除公司", notes = "删除公司")
    @PostMapping(value = "/delCompany")
    @MyLog(title = "删除公司",businessType = BusinessTypeEnum.delete)
    public ResponseBean delCompany(@RequestBody DelCompReq req) {
        try {
            //获取公司信息
            Map<String, Object> map = iCompanyService.SelectCompanyDetail(req.getCompId());
            if (map == null) {
                return ResponseBean.fail("记录不存在！");
            }
            int iRet = iCompanyService.DelCompany(req.getCompId());
            if (iRet > 0) {
                Long orgaId = Long.parseLong(map.get("orgaId").toString());

                OrganizationDto dto = organization.detail(orgaId);
                //组织机构禁用
                dto.setOrgaId(orgaId);
                dto.setOrgaName(dto.getOrgaName());
                dto.setUpdateTime(LocalDateTime.now());
                dto.setIsEnable(1);
                organization.UpdateOrganization(dto);
                return ResponseBean.success("删除成功！");
            } else if (iRet == -1) {
                return ResponseBean.fail("存在引用,不能删除！");
            } else {
                return ResponseBean.fail("删除失败！");
            }
        } catch (BusinessException exception) {
            return ResponseBean.fail("删除公司异常".concat(exception.getMessage()));
        }
    }


    /**
     * 查询公司列表
     *
     * @return
     * @auther lc 2023/5/11
     */
    @ApiOperation(value = "查询公司选择列表", notes = "查询公司选择列表")
    @GetMapping(value = "/getCompanyCheckList")
    public ResponseBean getCompanyList(@CurrentUser UserInfo user, @Valid CompReq req) {
        try {
            if (req.getOrgaPathIds() == null) {
                //获取人员组织机构
                Map<String, Object> staffDto = iStaffService.SelectStaffDetail(user.getUserid());
                String orgaPathIds = staffDto.get("orgaPathIds").toString();
                req.setOrgaPathIds(orgaPathIds);
            }
            List<Map<String, Object>> list = iCompanyService.GetCompanyCheckList(req);
            return ResponseBean.success(list);
        } catch (BusinessException exception) {
            return ResponseBean.fail("查询公司选择列表异常: ".concat(exception.getMessage()));
        }
    }

    /**
     * 查询公司详情
     *
     * @return
     * @auther lc 2023/5/10
     */
    @ApiOperation(value = "查询公司详情", notes = "查询公司详情")
    @GetMapping(value = "/selectCompanyDetail")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "compId", dataType = "Integer", value = "公司id")})
    public ResponseBean selectStaffDetail(Integer compId) {
        try {
            Map<String, Object> map = iCompanyService.SelectCompanyDetail(compId);

            return ResponseBean.success(map);
        } catch (BusinessException exception) {
            return ResponseBean.fail("查询公司详情异常: ".concat(exception.getMessage()));
        }
    }

    /**
     * 查询公司列表
     *
     * @return
     * @auther lc 2023/5/11
     */
    @ApiOperation(value = "分页查询公司列表", notes = "分页查询公司列表")
    @GetMapping(value = "/selectCompanyList")
    public ResponseModel selectCompanyList(@CurrentUser UserInfo user, @Valid CompPageReq req) {
        ResponseDataModel responseModel = new ResponseDataModel();
        try {
            if (req.getCurrPage() == null || req.getPageSize() == null) {
                req.setCurrPage(1);
                req.setPageSize(10);
            }
            if (req.getOrgaPathIds() == null) {
                //获取人员组织机构
                Map<String, Object> staffDto = iStaffService.SelectStaffDetail(user.getUserid());
                String orgaPathIds = staffDto.get("orgaPathIds").toString();
                req.setOrgaPathIds(orgaPathIds);
            }
            List<Map<String, Object>> list = iCompanyService.SelectCompanyPage(req);

            PageInfo pageInfo = new PageInfo(list, req.getPageSize());

            responseModel.setData(pageInfo);
            responseModel.setRcount(list.size());
        } catch (BusinessException exception) {

            responseModel.setMessage("分页查询公司列表异常: ".concat(exception.getMessage()));
            responseModel.setCode(exception.getCode());
        }
        return responseModel;
    }

    /**
     * 公司信息导出
     *
     * @return
     * @auther ygp 2023/6/12
     */
    @ApiOperation(value = "公司信息导出", notes = "公司信息导出接口", produces = "application/octet-stream")
    @GetMapping(value = "/CompanyRecExport")
    @ApiOperationSupport(ignoreParameters = {"currPage", "pageSize"})
    public ResponseBean CompanyRecExport(@CurrentUser UserInfo user, CompPageReq req, HttpServletResponse response) {
        try {
            if (req.getOrgaPathIds() == null) {
                //获取人员组织机构
                Map<String, Object> staffDto = iStaffService.SelectStaffDetail(user.getUserid());
                String orgaPathIds = staffDto.get("orgaPathIds").toString();
                req.setOrgaPathIds(orgaPathIds);
            }
            List<CompanyDto> list = iCompanyService.getList(req);
            if (list.size() == 0) {
                return ResponseBean.success("数据源为空");
            } else if (list.size() > 5000) {
                return ResponseBean.fail("记录超过5000，请重新选择查询条件");
            } else {
                ExcelUtils.exportExcel(list, "公司信息", "公司信息sheet", CompanyDto.class, "公司信息", response);
                return ResponseBean.success();
            }
        } catch (Exception e) {
            return ResponseBean.fail("公司信息导出异常");
        }
    }

}
